package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.dtos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author huyu
 */
@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录
     * @param dto 用户传过来的手机号和密码
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        if (StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())) {
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,dto.getPhone());
            ApUser apUser = getOne(wrapper);
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            String salt = apUser.getSalt();
            String dtoPassword = dto.getPassword() + salt;
            dtoPassword = DigestUtils.md5DigestAsHex(dtoPassword.getBytes(StandardCharsets.UTF_8));
            if (dtoPassword.equals(apUser.getPassword())) {
                String token = AppJwtUtil.getToken((long) apUser.getId());
                apUser.setSalt("");
                apUser.setPassword("");
                HashMap<String, Object> map = new HashMap<>();
                map.put("user",apUser);
                map.put("token",token);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            String token = AppJwtUtil.getToken(0l);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
